import { spliteMatrix } from './spliteMatrix';

/**
 * 获取 元素 的 位置 大小
 * @param {Element} el
 */
function getElementOffsetPosi(el) {
  let getcompEl = window.getComputedStyle(el);
  let matrixstr = getcompEl['transform'];

  let width = el.offsetWidth;
  let height = el.offsetHeight;
  return {
    offsetTop:
      matrixstr != 'none'
        ? spliteMatrix(matrixstr, 'translateY')
        : el.offsetTop,
    offsetLeft:
      matrixstr != 'none'
        ? spliteMatrix(matrixstr, 'translateX')
        : el.offsetLeft,
    width,
    // :
    //   el.offsetWidth -
    //   getNum(getcompEl.paddingLeft) -
    //   getNum(getcompEl.paddingRight)
    height,
    // :
    //   el.offsetHeight -
    //   getNum(getcompEl.paddingTop) -
    //   getNum(getcompEl.paddingBottom)
  };
}
window.getElementViewOffsetPosi = getElementViewOffsetPosi;

/**
 * 获取 当前元素 的 全局 位置 及 长宽信息
 * @param {HTMLElement} el
 */
function getElementViewOffsetPosi(el) {
  let viewOffsetPosi = getElementOffsetPosi(el);

  return {
    width: viewOffsetPosi['width'],
    height: viewOffsetPosi['height'],
    offsetTop: getbodyOffsetPosition(el, 'top'),
    offsetLeft: getbodyOffsetPosition(el, 'left'),
  };
}

function getbodyOffsetPosition(el, str) {
  let keys = 'offset' + str[0].toUpperCase() + str.substring(1);
  let translateDire = str == 'top' ? 'translateY' : 'translateX';
  // console.log(keys);
  let num = 0;
  let elclone = el;
  for (; elclone != null; ) {
    // console.log(elclone);
    // console.log(window.getComputedStyle(elclone));
    let matrixstr = window.getComputedStyle(elclone)['transform'];
    if (matrixstr != 'none') {
      let trans = spliteMatrix(matrixstr, translateDire);
      // console.log('tran', trans);
      num += Number(trans);
    }
    // console.log(elclone, elclone['offsetParent']);
    num += Number(elclone[keys]);
    // console.log('curMix', keys, num);
    elclone = elclone['offsetParent'];
  }
  return num;
}

/**
 * @param {HTMLElement} el
 */
function getElMargin(el) {
  return getElMarginOrPadding(el, 'margin');
}

/**
 * @param {HTMLElement} el
 */
function getElPadding(el) {
  return getElMarginOrPadding(el, 'padding');
}

/**
 *
 * @param {HTMLElement} el
 */
function getElMarginOrPadding(el, MP) {
  let elStyle = window.getComputedStyle(el);
  let ret = { top: '', right: '', bottom: '', left: '' };
  let direction = {
    top: 'Top',
    right: 'Right',
    bottom: 'Bottom',
    left: 'Left',
  };
  for (const key in direction) {
    if (Object.hasOwnProperty.call(direction, key)) {
      ret[key] = elStyle[`${MP}${direction[key]}`];
    }
  }

  return `${ret.top} ${ret.right} ${ret.bottom} ${ret.left}`;
}

export {
  getElementOffsetPosi,
  getElementViewOffsetPosi,
  getElMargin,
  getElPadding,
};
